import axios from 'axios'
import devConfig from './development.config'
import proConfig from './production.config'
import { HexMD5, b64hamcsha1 } from './upyn-hash-vue'

const envConfig = process.env.NODE_ENV === 'development' ? devConfig : proConfig
const { bucket, username, password, pathList, title, secret, logoUrl } =
  envConfig
export function upyunUpload({ file, watermark, info_type }) {
  const url = `https://v0.api.upyun.com/${bucket}`

  // 重命名文件
  const fileExtension = file.name.split('.').pop()
  const newFileName = `${new Date().getTime()}-${parseInt(
    Math.random() * 10000
  )}.${fileExtension}`
  const newFile = new File([file], newFileName, { type: file.type })

  const path = info_type ? pathList[info_type] : pathList[0]
  // if (process.env.NODE_ENV === 'production') {
  //   // 上传路径添加年月日 /pic/deptwo/gonggao/2024/10/09/1.jpg
  //   const now = new Date()
  //   path += `${now.getFullYear()}/${now.getMonth() + 1}/${now.getDate()}/`
  // }
  // console.log(path)

  /* 计算policy */
  const policyObj = {
    bucket: bucket,
    'save-key': `${path}/{filename}{.suffix}`,
    expiration: new Date().getTime() + 600 /* 过期时间，在当前时间+10分钟 */
  }
  const policy = btoa(JSON.stringify(policyObj))

  /* 计算 Authorization */
  const passwordMd5 = HexMD5.MD5(password).toString(HexMD5.enc.Hex)

  /* [Method-请求方法, URI-请求路径, policy] */
  const arr = ['POST', `/${bucket}`, policy]

  const authorization = `UPYUN ${username}:${b64hamcsha1(
    passwordMd5,
    arr.join('&')
  )}`

  const uploadData = {
    file: newFile,
    policy,
    authorization
  }

  let headers = {}
  if (watermark) {
    headers = {
      'Content-Secret': secret
    }
  }

  return new Promise((resolve, reject) => {
    axios({
      method: 'POST',
      url,
      data: uploadData,
      headers
    })
      .then((res) => {
        if (watermark) {
          resolve(title + res.url + logoUrl)
        } else {
          resolve(title + res.url)
        }
      })
      .catch((e) => {
        console.error('上传失败', e)
        reject('上传失败')
      })
  })
}
